package es.udc.pfc.davidparedes.web.pages.user;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;

import es.udc.pfc.davidparedes.model.storeservice.StoreService;
import es.udc.pfc.davidparedes.model.util.DuplicateInstanceException;
import es.udc.pfc.davidparedes.web.services.AuthenticationPolicy;
import es.udc.pfc.davidparedes.web.services.AuthenticationPolicyType;
import es.udc.pfc.davidparedes.web.util.UserSession;

@AuthenticationPolicy(AuthenticationPolicyType.ADMIN)
public class AddStore {
	
    @Property
    private String name;
    
    @Property
    private String address;
	
    @SessionState(create=false)
    private UserSession userSession;
    
    @Inject
    private StoreService storeService;
    
    @Component
    private Form addStoreForm;
    
    @Inject
    private Messages messages;
    
    Object onValidateFromAddStoreForm() {
    	
    	if (!addStoreForm.isValid()) {
            return this;
        }
    	
    	try {
			storeService.registerStore(name, address);
		} catch (DuplicateInstanceException e) {
			addStoreForm.recordError(messages.get("error-duplicate"));
		}
    	
    	return AdminStores.class;
    	
    }
    
}
